﻿using System;
using System.Net;
using System.Globalization;
using System.IO;

public class GeonamesWeather
{
    private readonly static string FindNearbyWeatherUrl =
        "http://ws.geonames.org/findNearByWeatherJSON?lat={0}&lng={1}&maxRows=10";

    public static string GetWeatherByLocation(double lat, double lng)
    {
        string formattedUri = String.Format(CultureInfo.InvariantCulture, FindNearbyWeatherUrl, lat, lng);

        HttpWebRequest webRequest = GetWebRequest(formattedUri);
        HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
        string jsonResponse = string.Empty;
        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
        {
            jsonResponse = sr.ReadToEnd();
        }
        return jsonResponse;
    }

    private static HttpWebRequest GetWebRequest(string formattedUri)
    {
        // Construct the request’s URL.  
        Uri serviceUri = new Uri(formattedUri, UriKind.Absolute);

        // Return a HttpWebRequest object.  
        return (HttpWebRequest)System.Net.WebRequest.Create(serviceUri);
    }
}
